package com.century.sjt.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ExpandableListView;
import android.widget.ListView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.century.sjt.R;
import com.century.sjt.adapter.PaydayTransactionRecordAdapter;
import com.century.sjt.adapter.payDayTransationAdapter;
import com.century.sjt.entity.DayTransaction;
import com.century.sjt.entity.TransactionRecord;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商家用户
 * 当日成交结算记录
 */
public class mTransaction_DayAccountFragment extends BaseFragment {
    private List<DayTransaction> mDataList;
    private ExpandableListView mListPtRecord;
    private int lastClick = -1;//上一次点击的group的position
    private payDayTransationAdapter mAdapter;
    String type="2";
    //    private Button loadMore;
    private Context mContext;

    private RequestQueue mQueue;
    private String pageSize="10";
    private int iCurrPage=1;
    private SwipeRefreshLayout mSwipeLayout;        //刷新组件
    private Handler mHandler;
    private Boolean isDataChangeOk=true;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.sjt_payday_transaction_fragment, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mContext=getActivity();
        mQueue = Volley.newRequestQueue(getActivity());

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        mAdapter.notifyDataSetChanged();
                        TipUtil.closeProgressDialog();
                        mSwipeLayout.setRefreshing(false);
                        break;
                    case 2:
                        isDataChangeOk=true;
                        mDataList.clear();
                        iCurrPage = 1;
                        getMonthList();
                        break;
                    case 3:
                        if(isDataChangeOk) {
                            mSwipeLayout.setRefreshing(true);
                            iCurrPage++;
                            getMonthList();
                        }
                        break;
                    case 4:
                        mAdapter.notifyDataSetChanged();
                        TipUtil.closeProgressDialog();
                        mSwipeLayout.setRefreshing(false);
                        break;

                }
            }
        };
        initView();
        initEvents();

//        getStoreDetail(merchantId);


    }

    private void initEvents() {

        mAdapter=new payDayTransationAdapter(mContext,mDataList,mHandler);
        mListPtRecord.setAdapter(mAdapter);
        //在drawable文件夹下新建了indicator.xml，下面这个语句也可以实现group伸展收缩时的indicator变化
        //expandList.setGroupIndicator(this.getResources().getDrawable(R.drawable.indicator));
        mListPtRecord.setGroupIndicator(null);//这里不显示系统默认的group indicator
        mListPtRecord.setAdapter(mAdapter);
        registerForContextMenu(mListPtRecord);//给ExpandListView添加上下文菜单
        mListPtRecord.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {
                // 当不滚动时
                if (i == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    if (absListView.getLastVisiblePosition() == absListView.getCount() - 1) {
                        //加载更多功能的代码
                        Message msg = new Message();
                        msg.what = 3;
                        mHandler.sendMessage(msg);
                    }
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }
        });

        mListPtRecord.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {

                if (mDataList.get(i).isSelsct()){
                    mDataList.get(i).setSelsct(false);
                    lastIsClick(i);
                }else {
                    mDataList.get(i).setSelsct(true);
                    getRecords(mDataList.get(i).getmDay(),i);
                }

                return true;
            }
        });
        //更多记录
//        View bottomView=getLayoutInflater().inflate(R.layout.social_zone_listview_bottom, null);
//        loadMore=(Button)bottomView.findViewById(R.id.social_zone_listview_bottom_load);
//        loadMore.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                loadMore.setEnabled(false);
//                loadMore.setText("加载中");
//                getRecords();
//
//            }
//        });
//        mListPtRecord.addFooterView(bottomView);

        //刷新组件
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Message msg = new Message();
                msg.what = 2;
                mHandler.sendMessage(msg);
            }
        });
        mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);

//        getRecords();
    }

    @Override
    public void onResume() {
//        getRecords();
        Message msg = new Message();
        msg.what = 2;
        mHandler.sendMessage(msg);
        super.onResume();
    }

    private void initView(){
        //刷新组件
        mSwipeLayout = (SwipeRefreshLayout)getView(). findViewById(R.id.activity_list_refesh);
        mQueue = Volley.newRequestQueue(mContext);
        mDataList = new ArrayList<>();
        mListPtRecord= (ExpandableListView)getView().findViewById(R.id.list_pt_record);
    }

    //获取日结算
    private void getRecords(final String month,final int i){
//        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.please_waitting),mContext);
        isDataChangeOk=false;
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.MerAmountEachDays, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    isDataChangeOk=true;
                    TipUtil.log("商家日结算交易订单", response, 1);
//                    loadMore.setText("加载更多");
//                    loadMore.setEnabled(true);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        List<TransactionRecord> mList = new ArrayList<>();
                        mList.clear();
                        JSONArray data = res.getJSONArray("data");
                        if (data.length()!= Constant.PAGESIZE) {
                            isDataChangeOk = false;
                            if (iCurrPage == 1 && data.length() == 0) {
//                                TipUtil.showToast("暂无交易记录", mContext);
                            } else {
//                                TipUtil.showToast("无更多数据",PayTransactionActivity.this);
                            }
                        }
                        for(int i=0;i<data.length();i++){
                            JSONObject dataObject=data.getJSONObject(i);
//                            Log.e("mian",dataObject.toString());
                            TransactionRecord transactionRecord=new TransactionRecord();
//
                            transactionRecord.setTxDate(dataObject.getString("tradeDate"));
                            transactionRecord.setTxAmt(dataObject.getString("tradeAmount"));

                            mList.add(transactionRecord);

                        }
                        mDataList.get(i).setmDataList(mList);
                    } else {//失败
                        TipUtil.showToast(message, mContext, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), mContext, 1);
                }
                TipUtil.closeProgressDialog();
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);

                lastIsClick(i);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), mContext, 1);
                TipUtil.closeProgressDialog();
                isDataChangeOk=true;
                iCurrPage--;
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences =mContext. getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("month",month);
                map.put("paging.pageSize", Constant.PAGESIZE+"");
                map.put("paging.currentPage",String.valueOf(iCurrPage));
                return map;
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences =mContext. getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }
    //获取日结算
    private void getMonthList(){
//        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.please_waitting),mContext);
        isDataChangeOk=false;
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.turnoverMonthList, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    isDataChangeOk=true;
                    TipUtil.log("接口返回", response, 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    JSONObject data = res.getJSONObject("data");
                    if (code.equals("200")) {//成功
                        JSONArray turnoverMonthList = data.getJSONArray("turnoverMonthList");
                        if (turnoverMonthList.length()!= Constant.PAGESIZE) {
                            isDataChangeOk = false;
                            if (iCurrPage == 1 && turnoverMonthList.length() == 0) {
//                                TipUtil.showToast("暂无交易记录", mContext);
                            } else {
//                                TipUtil.showToast("无更多数据",PayTransactionActivity.this);
                            }
                        }
                        for(int i=0;i<turnoverMonthList.length();i++){
                            String mDay = (String) turnoverMonthList.get(i);
                            DayTransaction dayTransaction = new DayTransaction();
                            dayTransaction.setmDay(mDay);
                            dayTransaction.setSelsct(false);
                            mDataList.add(dayTransaction);
                        }

                    } else {//失败
                        TipUtil.showToast(message, mContext, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), mContext, 1);
                }
                TipUtil.closeProgressDialog();
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), mContext, 1);
                TipUtil.closeProgressDialog();
                isDataChangeOk=true;
                iCurrPage--;
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences =mContext. getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("paging.pageSize", Constant.PAGESIZE+"");
                map.put("paging.currentPage",String.valueOf(iCurrPage));
                return map;
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences =mContext. getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }
    @Override
    public void onDestroy() {
        mQueue.cancelAll(this);
        super.onDestroy();
    }

    private void lastIsClick(int i){
        if(lastClick == -1)
        {
            mListPtRecord.expandGroup(i);
        }
        if(lastClick != -1 && lastClick != i)
        {
            mListPtRecord.collapseGroup(lastClick);
            mListPtRecord.expandGroup(i);
        }
        else if(lastClick == i)
        {
            if(mListPtRecord.isGroupExpanded(i))
                mListPtRecord.collapseGroup(i);
            else if(!mListPtRecord.isGroupExpanded(i))
                mListPtRecord.expandGroup(i);
        }
        lastClick = i;
    }
}
